package com.kh.pajx.sop.view.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;

import com.kh.pajx.sop.base.ModelDrivenBaseAction;
import com.kh.pajx.sop.domain.SysDepartment;
import com.kh.pajx.sop.domain.SysDeptArea;
import com.kh.pajx.sop.util.common.DwzAjaxResult;
import com.kh.pajx.sop.util.common.ValidatorUtils;
import com.kh.pajx.sop.util.page.QueryHelper;
import com.kh.pajx.sop.util.sop.PropertyValidate;
import com.opensymphony.xwork2.ActionContext;

/**
 * 部门信息Struts2逻辑控制器
 * @author:	azzcsimp
 * @Createdate:	2014年7月19日 上午2:36:08
 */
@Controller
@Scope("prototype")
public class SysDepartmentAction extends ModelDrivenBaseAction<SysDepartment> {

	private static final long serialVersionUID = -1257483672741591418L;
	
	/** 父级编码 */
	private String parentCode;
	private HttpServletRequest request;
	
	/** 列表 */
	public String main(){
		ActionContext.getContext().put("deptTree", sysDepartmentService.getDeptTreeJson());
		return "main";
	}
	
	/** 列表 */
	public String list(){
		new QueryHelper(SysDepartment.class,"dept")
		.addCondition(StringUtils.isNotEmpty(parentCode),"dept.parent.deptCode=?", parentCode)
		.addOrderProperty("dept.deptCode", true)
		.preparePageBean(sysDepartmentService, pageNum, numPerPage);;
		return "list";
	}
	
	/** 添加页面 */
	public String addUI(){
		// 准备数据：departmentList，显示为树状结构
		ActionContext.getContext().put("departmentList", sysDepartmentService.getAll());
		return "saveUI";
	}
	
	/** 添加 */
	public void add(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			//参数校验
			if(StringUtils.isNotBlank(parentCode)){
				 if (!ValidatorUtils.validateFixedLengthNumber(parentCode, 4,false)) {
						throw new Exception("上级部门编码不合法");
					}
				model.setParent(sysDepartmentService.getByCode(parentCode));
			}
			 if (!ValidatorUtils.validateSafeString(model.getDeptName(), 20, false)) {
					throw new Exception("部门名称输入不合法");
				}
			
			model.setDeptName(StringUtils.trim(model.getDeptName()));
			model.setDeptCode(sysDepartmentService.getDeptCode());
			sysDepartmentService.save(model);
			dwz.setStatusCode("200");
			dwz.setMessage("保存成功！");
			//dwz.setNavTabId("dept_jbsxBox");
			dwz.setRel("dept_jbsxBox");
			dwz.setCallbackType("closeCurrent");
			//dwz.setCloseDialog("dept_addUI");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("保存失败！<br>错误信息："+e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}
	
	/** 修改页面 */
	public String editUI(){
		SysDepartment department = sysDepartmentService.getById(model.getDeptId());
		List<SysDepartment> departmentList = sysDepartmentService.getAll();
		walkRemoveDept(department.getChildren(),departmentList);
		departmentList.remove(department);
		ActionContext.getContext().put("departmentList",departmentList);
		ActionContext.getContext().getValueStack().push(department);
		ActionContext.getContext().put("parentCode", department.getParent()==null?"":department.getParent().getDeptCode());
		return "saveUI";
	}
	
	private void walkRemoveDept(Collection<SysDepartment> children, List<SysDepartment> list){
		for(SysDepartment dept : children){
			list.remove(dept);
			walkRemoveDept(dept.getChildren(),list);
		}
	}
	
	/** 修改 */
	public void edit(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			//参数校验
			
			if(!ValidatorUtils.validateUUID(model.getDeptId(),false)){
		    	throw new Exception("部门编号不合法");
		    }
			 if (!ValidatorUtils.validateSafeString(model.getDeptName(), 20, false)) {
					throw new Exception("部门名称输入不合法");
			}
			SysDepartment department = sysDepartmentService.getById(model.getDeptId());
			if(StringUtils.isNotBlank(parentCode)){
				if (!ValidatorUtils.validateFixedLengthNumber(parentCode, 4,false)) {
					throw new Exception("上级部门编码不合法");
			}
				department.setParent(sysDepartmentService.getByCode(parentCode));
			}else{
				department.setParent(null);
			}
			department.setDeptName(StringUtils.trim(model.getDeptName()));
			
			sysDepartmentService.update(department);
			dwz.setStatusCode("200");
			dwz.setMessage("修改成功!");
			dwz.setRel("dept_jbsxBox");
			dwz.setCallbackType("closeCurrent");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("修改失败！<br>错误信息："+e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}
	/**给部门绑定地区*/
	public String bindAreaUI(){
		SysDepartment department = sysDepartmentService.getById(model.getDeptId());
		List<SysDepartment> departmentList = sysDepartmentService.getAll();
		List<SysDeptArea> deptAreaList=sysDeptAreaService.getSysDeptAreaByDeptCode(department.getDeptCode());
		walkRemoveDept(department.getChildren(),departmentList);
		departmentList.remove(department);
		ActionContext.getContext().put("departmentList",departmentList);
		ActionContext.getContext().put("deptAreaList",deptAreaList);
		ActionContext.getContext().getValueStack().push(department);
		ActionContext.getContext().put("parentCode", department.getParent()==null?"":department.getParent().getDeptCode());
		return "bindAreaUI";
	}
	/**绑定地区*/
	public void bindArea(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		request = ServletActionContext.getRequest();
		try {
			if(!ValidatorUtils.validateUUID(model.getDeptId(),false)){
		    	throw new Exception("部门编号不合法");
		    }
			String[] areaCodes=request.getParameterValues("areaCodes");
			SysDepartment department = sysDepartmentService.getById(model.getDeptId());
			List<SysDeptArea> deptAreaList=sysDeptAreaService.getSysDeptAreaByDeptCode(department.getDeptCode());//查出原部门绑定的地区
			List<SysDeptArea> newDeptAreaList=new ArrayList<SysDeptArea>();
			for(String areaCode:areaCodes){
				if(!ValidatorUtils.validateFixedLengthNumber(areaCode,4,false)){
			    	throw new Exception("管辖地区信息不合法");
			    }
				SysDeptArea deptArea=new SysDeptArea();
				deptArea.setAreaCode(areaCode);
				deptArea.setDeptCode(department.getDeptCode());
				newDeptAreaList.add(deptArea);
			}
			sysDeptAreaService.updateDeptArea(deptAreaList,newDeptAreaList);//更新部门和地区的关系
			/*for(SysDeptArea deptArea:deptAreaList){//将原关系删除
				sysDeptAreaService.delete(deptArea.getDeptAreaId());
			}
			for(String areaCode:areaCodes){
				SysDeptArea deptArea=new SysDeptArea();
				deptArea.setAreaCode(areaCode);
				deptArea.setDeptCode(department.getDeptCode());
				sysDeptAreaService.save(deptArea);
			}*/
			/*department.setDeptName(StringUtils.trim(model.getDeptName()));
			if(StringUtils.isNotEmpty(parentCode)){
				department.setParent(sysDepartmentService.getByCode(parentCode));
			}
			sysDepartmentService.update(department);*/
			dwz.setStatusCode("200");
			dwz.setMessage("修改成功!");
			dwz.setRel("dept_jbsxBox");
			dwz.setCallbackType("closeCurrent");
			DwzAjaxResult.josnMessage(dwz);
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("修改失败！<br>错误信息："+e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}
	
	/** 删除 */
	public void delete(){
		DwzAjaxResult dwz = new DwzAjaxResult();
		try {
			SysDepartment department = sysDepartmentService.getById(model.getDeptId());
			if (department.getChildren()!=null && department.getChildren().size()>0){	
				dwz.setMessage("删除失败!<br>错误信息：当前部门下包含<font color='red'>"+department.getChildren().size()+"</font>条子部门信息数据！");
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
				return;
			}
			
			
			long insideUserCount = sysInsideUserService.countUserByDeptCode(department.getDeptCode());
			if (insideUserCount > 0){	
				dwz.setMessage("删除失败!<br>错误信息：当前部门下包含<font color='red'>"+insideUserCount+"</font>条内部用户信息数据！");
				dwz.setStatusCode("300");
				DwzAjaxResult.josnMessage(dwz);
				return;
			}
			
			
			sysDepartmentService.delete(department.getDeptId());
			dwz.setStatusCode("200");
			dwz.setMessage("删除成功!");
			dwz.setRel("dept_jbsxBox");
			DwzAjaxResult.josnMessage(dwz);
			
		} catch (Exception e) {
			e.printStackTrace();
			dwz.setMessage("删除失败!<br>错误信息："+e.getMessage());
			dwz.setStatusCode("300");
			DwzAjaxResult.josnMessage(dwz);
		}
	}
	
	
	
	/** 查看 */
	public String show(){
		return "";
	}

	public String getParentCode() {
		return parentCode;
	}

	public void setParentCode(String parentCode) {
		this.parentCode = parentCode;
	}
	
	
	
}
